package com.tiancheng.trade.commom.core.utils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 腾讯云网关密钥对认证
 */
public class PlatformCloudApiAuth {
    private static final String CONTENT_CHARSET = "UTF-8";
    private static final String HMAC_ALGORITHM = "HmacSHA1";

    private static String sign(String secret, String timeStr) {
        try {
            //获取签名字符串
            String signStr = "date: " + timeStr + "\n" + "source: " + "source";
            Mac mac1 = Mac.getInstance(HMAC_ALGORITHM);
            byte[] hash;
            SecretKeySpec secretKey = new SecretKeySpec(secret.getBytes(CONTENT_CHARSET), mac1.getAlgorithm());
            mac1.init(secretKey);
            hash = mac1.doFinal(signStr.getBytes(CONTENT_CHARSET));
            //获取接口签名
            return new String(Base64.getEncoder().encode(hash));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Map<String, String> getAuthHeaders(String secretId, String secretKey) {
        //获取当前 GMT 时间
        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String timeStr = sdf.format(cd.getTime());
        String sig = sign(secretKey, timeStr);
        String authorization = "hmac id=\"" + secretId + "\", algorithm=\"hmac-sha1\", headers=\"date source\", signature=\"" + sig + "\"";
        Map<String, String> result = new HashMap<>();
        result.put("Authorization", authorization);
        result.put("Date", timeStr);
        result.put("source", "source");
        return result;
    }
}
